<?php

namespace Rjyst\RjPdf\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallCommand extends Command
{
    protected $signature = 'rj-pdf:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst PDF package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst PDF 扩展包...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst PDF 扩展包吗？这将删除相关文件和路由！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 删除模型文件
        $this->deleteModels();

        // 2. 删除控制器和仓库文件
        $this->deleteAdminFiles();

        // 3. 删除 Seeder 文件
        $this->deleteSeeders();

        // 4. 移除路由
        $this->removeRoutes();

        $this->info('🎉 RjYst PDF 扩展包卸载完成！');
        $this->line('');
        $this->line('<fg=yellow>⚠️  注意：</>');
        $this->line('• 数据库表和数据仍然保留 (pdf_images, pdf_image_coordinates, textbook_reads)');
        $this->line('• Category 模型的关联关系需要手动清理');
        $this->line('• 数据库配置文件需要手动清理');
        $this->line('• 如需完全清理，请手动删除相关配置');
    }

    protected function deleteModels()
    {
        $this->info('删除模型文件...');

        $models = [
            'PdfImage' => app_path('Models/Pdf/PdfImage.php'),
            'PdfImageCoordinate' => app_path('Models/Pdf/PdfImageCoordinate.php'),
            'TextbookRead' => app_path('Models/Pdf/TextbookRead.php'),
        ];

        foreach ($models as $name => $path) {
            if (File::exists($path)) {
                File::delete($path);
                $this->info("✅ 删除模型: {$name}");
            }
        }

        // 检查并删除空目录
        $pdfModelDir = app_path('Models/Pdf');
        if (File::isDirectory($pdfModelDir) && count(File::allFiles($pdfModelDir)) === 0) {
            File::deleteDirectory($pdfModelDir);
            $this->info('✅ 删除空目录: Models/Pdf');
        }
    }

    protected function deleteAdminFiles()
    {
        $this->info('删除管理后台文件...');

        $files = [
            'PdfImageController' => app_path('Admin/Controllers/Pdf/PdfImageController.php'),
            'PdfImage Repository' => app_path('Admin/Repositories/Pdf/PdfImage.php'),
        ];

        foreach ($files as $name => $path) {
            if (File::exists($path)) {
                File::delete($path);
                $this->info("✅ 删除文件: {$name}");
            }
        }

        // 检查并删除空目录
        $dirs = [
            app_path('Admin/Controllers/Pdf'),
            app_path('Admin/Repositories/Pdf'),
        ];

        foreach ($dirs as $dir) {
            if (File::isDirectory($dir) && count(File::allFiles($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->info("✅ 删除空目录: " . basename($dir));
            }
        }
    }

    protected function deleteSeeders()
    {
        $this->info('删除 Seeder 文件...');

        $seeders = [
            'PdfMenuSeeder' => database_path('seeders/PdfMenuSeeder.php'),
            'PdfDataSeeder' => database_path('seeders/PdfDataSeeder.php'),
            'TextBookReadDataSeeder' => database_path('seeders/TextBookReadDataSeeder.php'),
        ];

        foreach ($seeders as $name => $path) {
            if (File::exists($path)) {
                File::delete($path);
                $this->info("✅ 删除 Seeder: {$name}");
            }
        }
    }

    protected function removeRoutes()
    {
        $this->info('移除路由...');

        $routeFile = app_path('Admin/routes.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  routes.php 文件不存在');
            return;
        }

        $content = File::get($routeFile);

        // 移除 pdfImage 路由
        $content = preg_replace("/\s*\\\$router->resource\('pdfImage',\s*'Pdf\\\\PdfImageController'\);\s*/", '', $content);

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($routeFile, $content);
        $this->info('✅ 路由移除完成');
    }
}
